﻿using System;
using System.Collections.Generic;
using System.Text;

namespace PipePrinter
{
    public delegate void traceCallBack(string str);

    public class TraceHelper
    {
        public traceCallBack TraceCB = null;

        public TraceHelper(traceCallBack t)
        {
            TraceCB = new traceCallBack(t);
        }

        public TraceHelper()
        {
        }

        public void SetTraceCallback(traceCallBack trCB)
        {
            TraceCB = new traceCallBack(trCB);
        }

        public void traceLog(string s)
        {
            traceLog(s, false);
        }


        public void traceLog(string s, bool displayTime)
        {
            if (TraceCB != null)
            {

                string st = "";
                //zero terminate s
                int xz = s.IndexOf('\0');
                if (xz != -1)
                {
                    s = s.Substring(0, xz);
                }
                if (displayTime)
                {
                    DateTime dt = DateTime.Now;
                    st = string.Format("{0:hh:mm:ss}.{1:000}\t", dt, dt.Millisecond);
                    st += s + "\r\n";
                }
                else
                {
                    st += s + "\r\n";
                    //st = "----" + "\r\n" + s + "\r\n" + "----" + "\r\n";
                }
                TraceCB(st);
            }
        }

        public void traceException(Exception ex)
        {
            traceLog("EXCEPTION: \r\n" + "Message: " + ex.Message + "\r\n" + "Call Stack: " + ex.StackTrace);
        }
    }

}
